package com.dlc.apk.base

import android.app.AlarmManager
import android.app.Application
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import com.android.tony.defenselib.DefenseCrash
import com.android.tony.defenselib.handler.IExceptionHandler
import com.dlc.apk.api.ApiManager
import com.dlc.apk.dao.ObjectBox
import com.dlc.apk.ui.activity.MainActivity
import com.dlc.apk.utils.LogPlus
import com.jeremyliao.liveeventbus.LiveEventBus

import kotlin.system.exitProcess

open class BaseApp : Application(), IExceptionHandler {
    var uiHandler: Handler? = null
        private set

    override fun onCreate() {
        super.onCreate()
        instance = this
        uiHandler = Handler()
        init()
    }

    protected open fun init() {
        initEventBus()
        initServerApi()
        initDatabase()
    }

    private fun initEventBus() {
        LiveEventBus.config()
            .lifecycleObserverAlwaysActive(true) //true 整个生命周期（从onCreate到onDestroy）都可以实时收到消息, false 激活状态（Started）可以实时收到消息，非激活状态（Stoped）无法实时收到消息，需等到Activity重新变成激活状态，方可收到消息
            .autoClear(true) //配置在没有Observer关联的时候是否自动清除LiveEvent以释放内存（默认值false）
            .enableLogger(true) //启用日志
            .setContext(this) //如果广播模式有问题，请手动传入Context，需要在application onCreate中配置
    }

    private fun initServerApi() {
        ApiManager.instance
    }

    private fun initDatabase() {
        ObjectBox.init(this)
    }

    override fun onTerminate() {
        super.onTerminate()
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        DefenseCrash.initialize(this)
        DefenseCrash.install(this)
    }

    override fun onCaughtException(thread: Thread?, throwable: Throwable?, isSafeMode: Boolean, isCrashInChoreographer: Boolean) {
        throwable?.printStackTrace()
        LogPlus.e("###异常 -> " + LogPlus.getStackTraceInfo(throwable))

        if (isSafeMode) {
            LogPlus.d("###########onEnterSafeMode###########")
        }
        if (isCrashInChoreographer) {
            restartApp(0)
        }
    }

    fun restartApp(restartDelayTime: Long) {
        val mStartActivity = Intent(this, MainActivity::class.java)
        val mPendingIntentId = 123456
        val mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT)
        val mgr = this.getSystemService(ALARM_SERVICE) as AlarmManager
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
                mgr.setExactAndAllowWhileIdle(AlarmManager.RTC, if (restartDelayTime == 0L) System.currentTimeMillis() + 100 else System.currentTimeMillis() + restartDelayTime, mPendingIntent)
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT -> {
                mgr.setExact(AlarmManager.RTC, if (restartDelayTime == 0L) System.currentTimeMillis() + 100 else System.currentTimeMillis() + restartDelayTime, mPendingIntent)
            }
            else -> {
                mgr[AlarmManager.RTC, if (restartDelayTime == 0L) System.currentTimeMillis() + 100 else System.currentTimeMillis() + restartDelayTime] = mPendingIntent
            }
        }
        exitProcess(0)
    }

    fun runOnUiThread(runnable: Runnable) {
        if (Thread.currentThread() !== uiHandler!!.looper.thread) {
            uiHandler!!.post(runnable)
        } else {
            runnable.run()
        }
    }

    companion object {
        lateinit var instance: BaseApp
            private set
    }


}